package com.sqly.doc.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sqly.doc.R;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.gxy.gxy;
import com.sqly.doc.menu.qianyue.qianyue_add;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.TeamMember;
import com.sqly.doc.util.CreateBitmap;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.Url;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.util.WriteActivity;
import com.sqly.doc.view.StringUtils;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.Bind;
import butterknife.ButterKnife;
import cxy.com.validate.IValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.NotNull;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ContentType;

public class team_member_qm extends MyBaseActivity {
    //标题
    TextView title, uname;
    @Index(1)
    @NotNull(msg = "团队长姓名不能为空")
    @Bind(R.id.tdzxm)
    TextView tdzxm;
    @Index(2)
    @NotNull(msg = "团队长账号不能为空")
    @Bind(R.id.tdzzh)
    TextView tdzzh;
    LinearLayout back;
    TeamMember member;
    String url = "";
    ImageView sfysqm;
    String sfysqmpic = "";
    Context con = team_member_qm.this;
    ZLoadingDialog dialog;
    String flag ="1";

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_team_member_qm);
        ButterKnife.bind(this);
        Validate.reg(this);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        member = (TeamMember) getIntent().getExtras().getSerializable("member");
        url = HttpUrl.AddTdzQm;
        if(null != member && !StringUtils.isEmpty(member.getMember_code())){
            tdzzh.setText(member.getMember_code());
        }
        if(null != member && !StringUtils.isEmpty(member.getMember_name())){
            tdzxm.setText(member.getMember_name());
        }
        //医生签名
        sfysqm = (ImageView) findViewById(R.id.sfysqm);
        if (member != null && !StringUtils.isEmpty(member.getSfysqm())) {
            sfysqmpic = member.getSfysqm();
            try {
                sfysqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + sfysqmpic + ".jpg"));
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        sfysqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, WriteActivity.class).putExtra("class","team_member_qm.class"), 8);
            }
        });

        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        back = (LinearLayout)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        title.setText("团队长签名上传");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Validate.check(con, new IValidateResult() {
                    @Override
                    public void onValidateSuccess() {
                        saveData();
                    }

                    @Override
                    public void onValidateError(String msg, View view) {
                        view.setFocusable(true);
                        //Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
                        SweetAlertDialogUtil.WarningDialog(con, "提示", msg);
                    }

                    @Override
                    public Animation onValidateErrorAnno() {
//                        return ValidateAnimation.horizontalTranslate();
                        return null;
                    }
                });
            }
        });
        if(!StringUtils.isEmpty(member.getImg1())){
            //ImageLoader.getInstance().displayImage(Url.img_url()+member.getImg1(),sfysqm);
            try {
                ImageLoader.getInstance().displayImage(Url.newStaticurl(SharedPreferencesUtils.getParam(con, "token", "").toString(), "2" ,member.getImg1()),sfysqm);
            } catch (Exception e) {
                //e.printStackTrace();
            }
            flag ="0";
        }else{
            flag ="1";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else if (requestCode == 8) {
            byte[] bis = data.getByteArrayExtra("bitmap");
            Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
            sfysqm.setImageBitmap(bb);
            sfysqmpic = CreateBitmap.saveMyBitmap(bb);
            flag ="1";
        }
    }

    private void saveData(){
        if (StringUtils.isEmpty(member.getImg1()) && ("").equals(sfysqm)) {
            SweetAlertDialogUtil.WarningDialog(con, "提示", "团队长签名不能为空");
        }else {
            StringBuilder urlParams = new StringBuilder();
            if (NetWorkUtils.isNetworkConnected(con)) {
                RequestParams ps = new RequestParams();
//                ps.add("type", "2");
//                ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
//                ps.add("ysid", member.getMember_code());
//                ps.add("flag", flag);
//                team_member_qm.super.onlyYsqmImageUploadOperate(sfysqmpic, ps);
                try {
                    ps.put("img1", new File(Environment.getExternalStorageDirectory() + "/" + sfysqmpic + ".jpg"), ContentType.IMAGE_JPEG.getMimeType());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                urlParams.append("token=").append(SharedPreferencesUtils.getParam(this, "token", "").toString()).append("&");
                urlParams.append("ysid=").append(member.getMember_code()).append("&");
                urlParams.append("flag=").append(flag).append("&");
                urlParams.append("type=").append("2");

                AsyncHttpClient client = new AsyncHttpClient();
                ps.setUseJsonStreamer(false);
                ps.setForceMultipartEntityContentType(true);
                client.setURLEncodingEnabled(false);

                client.post(this,UserClient.getUploadAbsoluteUrl2(url + "?" + urlParams.toString()), ps, new AsyncHttpResponseHandler() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        dialog.show();
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        String content = new String(response);
                        dialog.dismiss();
                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                        if (ret.getCode().equals("200")) {
                            MyToastUtil.ShowToast(con, "保存成功");
                            finish();
                        }else{
                            MyToastUtil.ShowToast(con, ret.getInfo());
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                        dialog.dismiss();
                        MyToastUtil.ShowToast(con, "网络连接失败");
                    }
                });
            } else{
                MyToastUtil.ShowToast(con, "网络连接失败");
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }
}
